package org.vz.product.collect.maintain.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.management.MalformedObjectNameException;

import org.jolokia.client.BasicAuthenticator;
import org.jolokia.client.J4pClient;
import org.jolokia.client.exception.J4pException;
import org.jolokia.client.request.J4pExecRequest;
import org.jolokia.client.request.J4pExecResponse;
import org.jolokia.client.request.J4pReadRequest;
import org.jolokia.client.request.J4pReadResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.vz.product.collect.maintain.dao.AcquisitionDao;
import org.vz.product.collect.maintain.dao.AcquisitionTaskDao;
import org.vz.product.collect.maintain.dao.EventDao;
import org.vz.product.collect.maintain.dao.KettleTransDao;
import org.vz.product.collect.maintain.domain.Acquisition;
import org.vz.product.collect.maintain.domain.AcquisitionTask;
import org.vz.product.collect.maintain.domain.Event;
import org.vz.product.collect.maintain.domain.KettleTransformation;
import org.vz.product.collect.maintain.domain.MessageResult;
import org.vz.product.collect.maintain.domain.entity.StatResult;
import org.vz.product.collect.maintain.domain.entity.WaitReceiveTrans;
import org.vz.product.collect.maintain.service.ActiveMqService;
import org.vz.product.collect.maintain.util.StringUtil;

/**
 * @author lanxuyu
 * @CreateTime 2017年10月18日 下午12:36:42
 * @version 1.0.0
 * @description
 */
@Service
public class ActiveMqServiceImpl implements ActiveMqService {
	@Autowired
	EventDao eventDao;
	@Autowired
	AcquisitionDao acDao;
	@Autowired
	AcquisitionTaskDao acTaskDao;
	@Autowired
	KettleTransDao ktrDao;

	@SuppressWarnings("unchecked")
	@Override
	public List<MessageResult> totalMessageCount(String baseUrl, String startTime,
			String endTime) {
		List<MessageResult> result = new ArrayList<MessageResult>();
		J4pClient j4pclient = J4pClient.url(baseUrl).user("admin")
				.password("admin")
				.authenticator(new BasicAuthenticator().preemptive())
				.connectionTimeout(3000).build();
		J4pReadRequest request = null;
		J4pReadResponse response = null;
		J4pExecRequest exRequest = null;
		J4pExecResponse exRsponse = null;
		try {

			Event event = new Event();
			request = new J4pReadRequest(
					"org.apache.activemq:brokerName=localhost,type=Broker",
					"Queues");
			response = j4pclient.execute(request);
			List<Map<String, Object>> objectNames = (List<Map<String, Object>>) response
					.getValue();
			//System.out.println(startTime + ":::::" + endTime);
			Date start = StringUtil.stringToDate(startTime, "yyyy-MM-dd");
			Date end = StringUtil.stringToDate(endTime, "yyyy-MM-dd HH:mm:ss");
			for (Map<String, Object> map : objectNames) {
				MessageResult messageResult = new MessageResult();
				request = new J4pReadRequest("" + map.get("objectName"));
				response = j4pclient.execute(request);
				
				messageResult.msgSendingName = response.getValue("Name");
				exRequest = new J4pExecRequest(
						"org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName="
								+ messageResult.msgSendingName, "browse()");
				exRsponse = j4pclient.execute(exRequest);
				//System.out.println(StringUtil.toJsonString(exRsponse.getValue()));
				List<Map<String, Object>> details = (List<Map<String, Object>>) exRsponse
						.getValue();
				long unqueueCount = 0;
				for (Map<String, Object> queueDetail : details) {
					String JMSTimestamp = (String) queueDetail
							.get("JMSTimestamp");
					Date formatJMSTimestamp = formatJMSTimestamp(JMSTimestamp);

					if (formatJMSTimestamp.getTime() > start.getTime()
							&& formatJMSTimestamp.getTime() < end.getTime()) {
						unqueueCount += 1;
					}
				}
				messageResult.msgacceptNum = (int) unqueueCount;
				// 英文名
				event.setEventName(response.getValue("Name"));
				List<Event> events = eventDao.getSQLManager().select(
						"event.selectByName", Event.class, event);

				if (events.size() > 0) {
					messageResult.receiveEventNameCN = events.get(0).getEventCN();
				}else{
					messageResult.receiveEventNameCN="消息通道";
				}
				result.add(messageResult);
			}
		} catch (MalformedObjectNameException e) {
			e.printStackTrace();
			return result;
		} catch (J4pException e) {
			e.printStackTrace();
			return result;
		}
		return result;
	}

	public Date formatJMSTimestamp(String time) {
		String tzId = TimeZone.getDefault().getID();
		TimeZone tz = TimeZone.getTimeZone(tzId);
		SimpleDateFormat formatter = new SimpleDateFormat(
				"yyyy-MM-dd'T'HH:mm:ss");
		formatter.setTimeZone(tz);
		try {
			return formatter.parse(time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see org.vz.product.collect.maintain.service.ActiveMqService#waitReceiveKtr(java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public StatResult<Map<String, Object>> waitReceiveKtr(String baseUrl, String startTime, String endTime) {
		
		J4pClient j4pclient = J4pClient.url(baseUrl).user("admin")
				.password("admin")
				.authenticator(new BasicAuthenticator().preemptive())
				.connectionTimeout(3000).build();
		J4pReadRequest request = null;
		J4pReadResponse response = null;
		J4pExecRequest exRequest = null;
		J4pExecResponse exRsponse = null;
		Map<String,Object> data=new HashMap<>();
		StatResult<Map<String,Object>> statResult = new StatResult<>();
		try {

			Event event = new Event();
			int totalCount=0;
			List<WaitReceiveTrans> wrTrs=new ArrayList<>();
			request = new J4pReadRequest(
					"org.apache.activemq:brokerName=localhost,type=Broker",
					"Queues");
			response = j4pclient.execute(request);
			@SuppressWarnings("unchecked")
			List<Map<String, Object>> objectNames = (List<Map<String, Object>>) response.getValue();
			
			Date start = StringUtil.stringToDate(startTime, "yyyy-MM-dd");
			Date end = StringUtil.stringToDate(endTime, "yyyy-MM-dd HH:mm:ss");
			for (Map<String, Object> map : objectNames) {
				
				request = new J4pReadRequest("" + map.get("objectName"));
				response = j4pclient.execute(request);
				event.setEventName(response.getValue("Name"));
				List<Acquisition> acquisitions = acDao.getSQLManager().select("acquisition.selectByEventName", Acquisition.class,event);
				if(acquisitions.size()>0){
					WaitReceiveTrans waitReceiveTrans = new WaitReceiveTrans();
					waitReceiveTrans.setAcId(acquisitions.get(0).getCode());
					waitReceiveTrans.setAcName(acquisitions.get(0).getName());
					AcquisitionTask acquisitionTask = new AcquisitionTask();
					acquisitionTask.setAcquisitioncode(waitReceiveTrans.getAcId());		
					List<AcquisitionTask> acTasks = acTaskDao.getSQLManager().select("acquisition.getActask", AcquisitionTask.class, acquisitionTask);
					if(acTasks.size()>0){
						KettleTransformation ktrTrans = ktrDao.getSQLManager().select("transformation.selectById", KettleTransformation.class, acTasks.get(0)).get(0);
						waitReceiveTrans.setKtrId(ktrTrans.getIdTransformation());
						waitReceiveTrans.setKtrName(ktrTrans.getName());
					}
					exRequest = new J4pExecRequest(
							"org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName="
									+ response.getValue("Name"), "browse()");
					exRsponse = j4pclient.execute(exRequest);
					@SuppressWarnings("unchecked")
					List<Map<String, Object>> details = (List<Map<String, Object>>) exRsponse.getValue();
					int unqueueCount = 0;
					for (Map<String, Object> queueDetail : details) {
						String JMSTimestamp = (String) queueDetail
								.get("JMSTimestamp");
						Date formatJMSTimestamp = formatJMSTimestamp(JMSTimestamp);
						//System.out.println(start.getTime() + ":::::" + formatJMSTimestamp.getTime() + ":::::" +end.getTime());
						if (formatJMSTimestamp.getTime() > start.getTime()
								&& formatJMSTimestamp.getTime() < end.getTime()) {
							unqueueCount += 1;
						}
					}
					waitReceiveTrans.setMsgCount(unqueueCount);
					totalCount+=unqueueCount;
					wrTrs.add(waitReceiveTrans);
				}
			}
			
			data.put("detail", wrTrs);
			data.put("totalCount", totalCount);
			
			statResult.setData(data);
			statResult.setMsg("查询成功!");
			statResult.setStatus(1);
			
		} catch (MalformedObjectNameException e) {
			e.printStackTrace();
			statResult.setMsg("查询失败!");
			statResult.setStatus(0);
			return statResult;
		} catch (J4pException e) {
			e.printStackTrace();
			statResult.setMsg("查询失败!");
			statResult.setStatus(0);
			return statResult;
		}
		return statResult;
	}

}
